package com.alex.distributedlockredis.simplelock;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;

@RestController
public class SeckillControllerAlex008 {

    private final RedisLockAlex008 redisLock;
    
    // 模拟商品库存
    private int stock = 100;
    
    public SeckillControllerAlex008(RedisLockAlex008 redisLock) {
        this.redisLock = redisLock;
    }

    @PostMapping("/seckill")
    public String seckill() {
        // 生成唯一的请求标识
        String requestId = UUID.randomUUID().toString();
        String lockKey = "seckill:lock";
        
        try {
            // 尝试获取锁，等待10秒
            boolean locked = redisLock.tryLock(lockKey, requestId, 10);
            if (!locked) {
                return "抢购失败，请稍后重试";
            }
            
            // 检查库存，模拟秒杀逻辑
            if (stock > 0) {
                stock--;
                return "抢购成功，剩余库存：" + stock;
            } else {
                return "商品已售罄";
            }
        } finally {
            // 释放锁
            redisLock.releaseLock(lockKey, requestId);
        }
    }
}